
import Relay from "react-relay";

import {type} from './type';

import {message} from 'antd';

/**
 *  http 请求
 *  参数 : 【
 *          m:mutation，[必需]
 *          paramIn:输入参数，[必需]
 *          {error:错误回调,success：成功回调}，[随意]
 *          nName：mutation名称  [随意]
 *         】
 */
function http(m,paramIn,{error,success},mName){
    const t = type(paramIn);
    if(typeof mutation !== "function"){ throw Error("mutation is not a function"); }
    else if(t !== "object"){ throw Error(`paramIn error , is a ${t}，should is a object`); }

    Relay.Store.commitUpdate(
        new m(paramIn,{
            onFailure:(e)=>{
                error ? error(e) : message.error("当前网络链接失败，请稍后再试");
            },
            onSuccess:(r)=>{
                if(mName != undefined) {
                    //尝试处理数据格式，向下挖
                    try {
                        let d  = r[mName][mName];
                        if(d.errorCode == "0"){
                            success && success(d);
                        }else if(d.errorCode == "500"){
                            message.error("服务器错误，请联系系统管理员");
                        }else{
                            const t = d.value || "未知错误";
                            message.error(t);
                        }
                    } catch (e) {
                        success && success(r);
                    }
                }
            }
        })
    )
}

export {http}